/**
 * Created by Brook on 2020/4/9.
 */

(function () {
    var async = require('async');
    var moment = require('moment');
    var sql_config = require('../../serverconfig.js');
    var model_sql = require('../../tool/db_helper.js').init(sql_config.Model_Config);
    var SQL_TXT = sql_config.SQL_TXT;
    var uuid = require('node-uuid');



    //接收请求 -  查询中心列队数据 - 取任务
    exports.post_getdata = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //判断是否有未结束的任务
            check_task:['check_pars', function (cb, result) {
                var num = 1;
                //判断是否有数量参数
                if (result.check_pars.num) {
                    num = result.check_pars.num;
                };
                model_sql.query(SQL_TXT.check_task,[result.check_pars.appid, Number(num)],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //查询数据
            get_data:['check_task', function (cb, result) {
                if (result.check_task.length ==0) {
                    var num = 1;
                    //判断是否有数量参数
                    if (result.check_pars.num) {
                        num = result.check_pars.num;
                    };
                    model_sql.query(SQL_TXT.parsing_get_data,[Number(num)],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb(null, result.check_task);
                };
            }],
            //判断中心列队中是否有任务
            check_data:['get_data', function (cb, resulrt) {
                if (resulrt.get_data.length == 0) {
                    var data = {
                        "message": "请求成功",
                        "data": {
                            "code": 21,
                            "message": '中心列表无数据'
                        }
                    };
                    console.log("Response request data success ...")
                    res.json(data);
                    cb('中心列表中无数据')
                } else {
                    cb(null, [])
                };
            }],
            //修改数据状态
            up_data:['check_data', function (cb, result) {
                if (result.check_task.length ==0) {
                    //获取数据ID，用于修改parsingstate
                    var idlist = [];
                    for (var i in result.get_data) {
                        idlist.push(result.get_data[i].id);
                    };
                    model_sql.query(SQL_TXT.parsing_up_data,[result.check_pars.appid,idlist],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb(null, []);
                };
            }],
            //整理输出数据 - 待完善
            output_data:['up_data', function (cb, result) {
                var data = result.get_data;
                cb(null, data);
            }],
            //回传数据
            response_data:['output_data', function (cb, result) {
                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": result.output_data
                    }
                };
                console.log("Response request data success ...")
                res.json(data);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                var r = {code:0,message:results.check_pars};
                //console.log(r);
            };
        });
    }


    //接收请求 - 写入模型参数相关信息 - 写入
    exports.post_insertinfo = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            get_id:['check_pars', function (cb, result) {
                var uuid = result.check_pars.uuid;

                model_sql.query(SQL_TXT.get_modellist,[uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            get_listid:['get_id', function (cb, result) {
                if (result.get_id.length == 0) {
                    var data = {
                        "message": "请求成功",
                        "data": {
                            "code": 201,
                            "message": '无效的uuid',
                        }
                    };
                    console.log("Response request data success ...")
                    res.json(data);
                } else {
                    model_sql.query(SQL_TXT.get_modelinfo,[result.get_id[0].id],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }],
            insert_listid:['get_listid', function (cb, result) {
                if (result.get_listid.length == 0) {
                    var info = [];
                    info = [
                        result.get_id[0].id,
                        ,
                        ,
                        ,
                        moment().format('YYYYMMDD'),
                        moment().format('YYYY-MM-DD HH:mm:ss')
                    ];
                    model_sql.query(SQL_TXT.insert_modelinfo, [info],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result.insertId);
                    });
                } else {
                    cb(null, result.get_listid[0].id);
                };
            }],
            update_list:['insert_listid', function (cb, result) {
                var info_id = result.insert_listid;
                var data = result.check_pars;
                var setdata = '';
                for (var i in data){
                    if (i != 'uuid'){
                        setdata += i + " = '" + data[i] + "', "
                    };
                };
                setdata = setdata.substr(0,setdata.length-2);

                var UpSql = SQL_TXT.update_modelinfo + setdata +' WHERE id = '+info_id+';';
                model_sql.query(UpSql,function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result.insertId);
                });
            }],
            //回传数据
            response_data:['update_list', function (cb, result) {
                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": []
                    }
                };
                console.log("Response request data success ...")
                res.json(data);
                cb()
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                var r = {code:0,message:results.check_pars};
                //console.log(r);
            };
        });
    }


    //接收请求 - 查询模型状态以及相关参数 - 查询
    exports.post_status = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //查询数据
            get_status_list:['check_pars', function (cb, result) {
                var info = result.check_pars;
                if (info.fileId || info.filepath || info.uuid) {
                    //生成查询条件
                    var generate = '';
                    for(var i in result.check_pars) {
                        if (i == 'fileId' || i == 'filepath' || i == 'uuid') {
                            generate += i+" = " + "'" +result.check_pars[i]+ "' AND ";
                        };
                    };
                    //处理查询条件
                    var target = 'AND '
                    var start = generate.length-target.length;
                    var arr = generate.substr(start,target.length);
                    if(arr == target){
                        generate = generate.substring(0,generate.length-4);
                    };
                    //查询数据
                    model_sql.query(SQL_TXT.get_statue_list + generate,function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb(null, []);
                };
            }],
            //查询数据
            get_status_info:['get_status_list', function (cb, result) {
                var info = result.check_pars;
                if (info.modelId || info.filename || info.modelName) {
                    //生成查询条件
                    var generate = '';
                    for(var i in result.check_pars) {
                        if (i == 'modelId' || i == 'filename' || i == 'modelName') {
                            generate += i+" = " + "'" +result.check_pars[i]+ "' AND ";
                        };
                    };
                    //处理查询条件
                    var target = 'AND '
                    var start = generate.length-target.length;
                    var arr = generate.substr(start,target.length);
                    if(arr == target){
                        generate = generate.substring(0,generate.length-4);
                    };
                    //查询数据
                    model_sql.query(SQL_TXT.get_statue_info + generate,function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb(null, []);
                };
            }],
            //整合数据查询 列表
            get_status_list_map:['get_status_info', function (cb, result) {
                if (result.get_status_list.length != 0) {
                    var map = {};
                    for (var i in result.get_status_list) {
                        map[result.get_status_list[i].id] = result.get_status_list[i];
                    };
                    cb(null, map);
                } else {
                    cb(null, []);
                };
            }],
            get_integration_list:['get_status_list_map', function (cb, result) {
                if (result.get_status_list.length != 0) {
                    var map = result.get_status_list_map;
                    var listid = [];
                    for (var i in result.get_status_list) {
                        listid.push(result.get_status_list[i].id);
                    };
                    model_sql.query(SQL_TXT.get_integration_info,[listid],function(db_err,db_result){
                        if (db_err) {
                            cb(db_err);
                        } else {
                            async.forEach(db_result,function(each_item,each_callback){
                                Object.keys(each_item).forEach(function(key,i,v){
                                    if (map[each_item.listid]){
                                        map[each_item.listid][key] = each_item[key];
                                    };
                                });
                                each_callback();
                            },function(each_err){
                                each_err?cb(each_err):cb(null, map);
                            });
                        };
                    });
                } else {
                    cb(null, []);
                };
            }],
            //整合数据查询 参数
            get_status_info_map:['get_integration_list', function (cb, result) {
                if (result.get_status_info.length != 0) {
                    var map = {};
                    for (var i in result.get_status_info) {
                        map[result.get_status_info[i].listid] = result.get_status_info[i];
                    };
                    cb(null, map);
                } else {
                    cb(null, []);
                };
            }],
            get_integration_info:['get_status_info_map', function (cb, result) {
                if (result.get_status_info.length != 0) {
                    var map = result.get_status_info_map;
                    var listid = [];
                    for (var i in result.get_status_info) {
                        listid.push(result.get_status_info[i].listid);
                    };
                    model_sql.query(SQL_TXT.get_integration_list,[listid],function(db_err,db_result){
                        if (db_err) {
                            cb(db_err);
                        } else {
                            async.forEach(db_result,function(each_item,each_callback){
                                Object.keys(each_item).forEach(function(key,i,v){
                                    if (map[each_item.id]){
                                        map[each_item.id][key] = each_item[key];
                                    };
                                });
                                each_callback();
                            },function(each_err){
                                each_err?cb(each_err):cb(null, map);
                            });
                        };
                    });
                } else {
                    cb(null, []);
                };
            }],
            //整理数据
            finishing_data:['get_integration_info', function (cb, result) {
                var list = [];
                var info = [];
                var map = {};
                for (var i in result.get_integration_list) {
                    list.push(result.get_integration_list[i])
                };
                for (var i in result.get_integration_info) {
                    info.push(result.get_integration_info[i])
                };
                var arr = list.concat(info);
                for (var i in arr) {
                    map[arr[i].id] = arr[i];
                };
                async.forEach(arr,function(each_item,each_callback){
                    if (map[each_item.id]){
                        map[each_item.id] = each_item;
                    };
                    each_callback();
                },function(each_err){
                    each_err?cb(each_err):cb(null, map);
                });
            }],
            //回传数据
            response_data:['finishing_data', function (cb, result) {
                var map = result.finishing_data;
                var list = [];
                for (var i in map) {
                    list.push(map[i]);
                };

                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": list
                    }
                };
                console.log("Response request data success ...")
                res.json(data);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                var r = {code:0,message:results.check_pars};
                //console.log(r);
            };
        });
    }


    //接收请求 - 根据MD5检查模型是否解析
    exports.post_checkmd5 = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            check_md5:['check_pars', function (cb, result) {
                model_sql.query(SQL_TXT.get_checkmd5, [result.check_pars.md5],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            return_req:['check_md5', function (cb, result) {
                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": '模型待解析'
                    }
                };
                if (result.check_md5.length != 0) {
                    data.data.code = 201;
                    data.data.data = '模型已解析';
                }
                console.log("Response request data success ...")
                res.json(data);
                cb(null, []);
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                var r = {code:0,message:results.check_pars};
                //console.log(r);
            };
        });
    }


    //生成uuid
    exports.post_uuid = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            create_uuid:['check_pars', function (cb, result) {
                let model_data = [];
                model_data = [
                    uuid.v1(),
                    '0',
                    '',
                    '0',
                    '',
                    '',
                    '',
                    result.check_pars.appid,
                    '1',
                    moment().format('YYYYMMDD'),
                    moment().format('YYYY-MM-DD HH:mm:ss')
                ];
                model_sql.query(SQL_TXT.create_uuid, model_data,function(db_err,db_result){
                    db_err?cb(db_err):cb(null,model_data);
                });
            }],
            return_req:['create_uuid', function (cb, result) {
                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": {uuid:result.create_uuid[0]}
                    }
                };
                console.log("Response request data success ...")
                res.json(data);
                cb(null, []);
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                var r = {code:0,message:results.check_pars};
                //console.log(r);
            };
        });
    }


    //【修改】 - 选择解析任务
    exports.post_choicetask = function(req, res) {
        async.auto({
            check_pars:function (cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body);
            },
            //判断是否有未结束的任务
            check_task:['check_pars', function (cb, result) {
                var num = 1;
                model_sql.query(SQL_TXT.check_task,[result.check_pars.appid, Number(num)],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //查询数据
            get_data:['check_task', function (cb, result) {
                if (result.check_task.length ==0) {
                    model_sql.query(SQL_TXT.choice_parsing_get_data,[result.check_pars.uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    var data = {
                        "message": "请求成功",
                        "data": {
                            "code": 200,
                            "data":result.check_task,
                            "message": '请先解绑任务'
                        }
                    };
                    console.log("Response request data success ...")
                    res.json(data);
                    cb('中心列表中无数据')
                };
            }],
            //判断中心列队中是否有任务
            check_data:['get_data', function (cb, resulrt) {
                if (resulrt.get_data.length == 0) {
                    var data = {
                        "message": "请求成功",
                        "data": {
                            "code": 21,
                            "message": '中心列表无数据'
                        }
                    };
                    console.log("Response request data success ...")
                    res.json(data);
                    cb('中心列表中无数据')
                } else {
                    cb(null, [])
                };
            }],
            //修改数据状态
            up_data:['check_data', function (cb, result) {
                if (result.check_task.length ==0) {
                    //获取数据ID，用于修改parsingstate
                    model_sql.query(SQL_TXT.choice_parsing_up_data,[result.check_pars.appid,result.check_pars.uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb(null, []);
                };
            }],
            //整理输出数据 - 待完善
            output_data:['up_data', function (cb, result) {
                var data = result.get_data;
                cb(null, data);
            }],
            //回传数据
            response_data:['output_data', function (cb, result) {
                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": result.output_data
                    }
                };
                console.log("Response request data success ...")
                res.json(data);
                cb(null, [])
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                var r = {code:0,message:results.check_pars};
                //console.log(r);
            };
        });
    }


}).call(this);
